package top.hepingan.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.Bottle;
import top.hepingan.java.entity.Dto.Pickupdto;
import top.hepingan.java.entity.Dto.pickupRes;
import top.hepingan.java.entity.Muser;
import top.hepingan.java.entity.Pickup;
import top.hepingan.java.entity.Reply;
import top.hepingan.java.entity.Res.ReplRes;
import top.hepingan.java.mapper.BottleMapper;
import top.hepingan.java.mapper.MuserMapper;
import top.hepingan.java.mapper.PickupMapper;
import top.hepingan.java.mapper.ReplyMapper;
import top.hepingan.java.service.Impl.service.IPickupService;
import top.hepingan.java.utils.UserUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/HistoryBottle")
@RestController
@Slf4j
@RequiredArgsConstructor
public class HistoryBottle {
    @Autowired
    private IPickupService pickupService;
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private BottleMapper bottleMapper;
    @Autowired
    private PickupMapper pickupMapper;
    @Autowired
    private MuserMapper muserMapper;


    /**
     * 展示漂流瓶的所以评论+ID
     *
     * @return
     */
    @GetMapping("/list")
    public Result list(Bottle  bottle)
    {
        long id=UserUtils.getCurrentLoginId();
        //发送漂流瓶ID-> 找到回复表 -我是单体的-也就是不需要维护留言关系
        if(bottle.getId()== null)
        {
            return Result.error("参数错误：bottleId不能为空");
        }
        //直接以瓶子为载体，直接显示回复内容+发送者名字 -如果是瓶子主人，前端来做判断
        LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reply::getBottleId, bottle.getId());
        queryWrapper.orderByDesc(Reply::getCreateTime);
        queryWrapper.and(wrapper->wrapper.eq(
          Reply::getStaticq,1)
                .or()
                .eq(Reply::getSenderId, id)
        );

        List<Reply> list = replyMapper.selectList(queryWrapper);
        if(list.isEmpty())
        {
            return Result.ok().setData(list);
        }
        //拿取发起人id集合
        List<ReplRes> listres=new ArrayList<>();
        list.stream().forEach(  reply -> {
          ReplRes res=new ReplRes();
          BeanUtils.copyProperties(reply,res);
          /// 获取回复者ID
          Long replyUserId = reply.getSenderId();
          Muser replyUser = muserMapper.selectById(replyUserId);
          res.setUser(replyUser);
          /// 判断是不是漂流瓶主人
          res.setOwner(replyUserId.equals(bottle.getUserId()));
          listres.add(res);

      });
        return Result.ok(" 获取成功").setData(listres);
    }

    /**
     * 获取与我有关历史漂流瓶
     * @return
     */
    @GetMapping("/getHistoryBottle")
    public Result getHistoryBottle() {
        Long userId = UserUtils.getCurrentLoginId();
        List<pickupRes> res=pickupService.getHistoryBottle(userId);
        res.forEach(resq -> {
            resq.setUserName(muserMapper.selectById(resq.getUserId()).getNickname());
        });
        return Result.ok().setData( res);
    }
    /**
     * 查看漂流瓶
     * @return
     */
    @GetMapping("/lookBottle")
    public Result lookBottle(Pickup pickup) {
        // 1. 参数校验
        if (pickup == null || pickup.getBottleId() == null) {
            return Result.error("参数错误：bottleId不能为空");
        }

        Long bottleId = pickup.getBottleId();

        // 2. 查询漂流瓶
        Bottle bottle = bottleMapper.selectById(bottleId);
        if (bottle == null) {
            return Result.error("漂流瓶不存在或已被删除");
        }

        // 3. 获取当前用户ID与投递者ID
        Long currentUserId = UserUtils.getCurrentLoginId();
        Long tdzUserId = bottle.getUserId();

        // 4. 查询双方所有回复记录（双向消息）
        LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reply::getBottleId, bottleId)
                .and(wrapper -> wrapper
                        .and(w1 -> w1.eq(Reply::getSenderId, currentUserId)
                                .eq(Reply::getReceiverId, tdzUserId))
                        .or(w2 -> w2.eq(Reply::getSenderId, tdzUserId)
                                .eq(Reply::getReceiverId, currentUserId))
                )
                .orderByAsc(Reply::getCreateTime);

        List<Reply> replyList = replyMapper.selectList(queryWrapper);

        // 5. 返回结果
        return Result.ok().setData(replyList);
    }

    /**
     * 捞取人回复漂流瓶
     * @return
     */
    @PostMapping("/replyBottle")
    public Result replyBottle(@RequestBody  Reply reply) {
        Long userId = UserUtils.getCurrentLoginId();
        Bottle bootle= bottleMapper.selectById(reply.getBottleId());
        //投递者ID-发送给他 -发送人的ID有了
        Long tdzuserid=bootle.getUserId();
        reply.setCreateTime(LocalDateTime.now());
        reply.setSenderId(userId);
        reply.setReceiverId(tdzuserid);
        int i=replyMapper.insert(reply);
        if(i==0){
            return Result.error("回复失败");
        }

        return Result.ok();
    }


    /// //////////////
    /// //////
    /// /////
    /// ////
    /// //////
    /// ////////
    /// //////////////
    /// //////
    /// /////
    /// ////
    /// //////
    /// ////////

    /// //////////////
    /// //////
    /// /////
    /// ////
    /// //////
    /// ////////
    /**
     * 我投递的漂流瓶
     *
     */
    @GetMapping("/myThrowBottle")
    public Result myThrowBottle() {
        Long userId = UserUtils.getCurrentLoginId();
        LambdaQueryWrapper<Bottle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bottle::getUserId, userId);
        queryWrapper.ne(Bottle::getStatus, 3);
        List<Bottle> list = bottleMapper.selectList(queryWrapper);
        return Result.ok().setData(list);
    }
    /**
     * 与我建立关系的人类
     */
    @GetMapping("/myRelation")
    public Result myRelation(Pickupdto  pickup) {
        Long userId = UserUtils.getCurrentLoginId();
        LambdaQueryWrapper<Pickup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Pickup::getBottleId, pickup.getBottleId());
        List<Pickup> list = pickupMapper.selectList(queryWrapper);
        List<Long> ids=list.stream().map(Pickup::getPickerId).toList();
        /// 返回 捞取者ID+名字和信息
        // 返回 捞取者ID + 名字和信息
        List<Pickupdto> listres = ids.stream()
                .map(id -> {
                    Muser muser = muserMapper.selectById(id);
                    Pickupdto pickupdto = new Pickupdto();
                    pickupdto.setBottleId(pickup.getBottleId());
                    pickupdto.setUserid(id);
                    pickupdto.setUsername(muser != null ? muser.getNickname() : "未知用户");
                    pickupdto.setPickerId(id);
                    pickupdto.setPickupTime(pickup.getPickupTime());
                    return pickupdto;
                })
                .toList();


        return Result.ok().setData(listres);
    }

    /**
     * my漂流瓶详情
     */
    @GetMapping("/mylookBottle")
    public Result mylookBottle(Pickupdto pickup) {
        // 1. 参数校验
        if (pickup == null || pickup.getBottleId() == null || pickup.getUserid() == null) {
            return Result.error("参数错误：bottleId和userId不能为空");
        }

        Long bottleId = pickup.getBottleId();
        Long targetUserId = pickup.getUserid(); // 拾取者ID
        Long currentUserId = UserUtils.getCurrentLoginId(); // 当前登录用户（应为瓶主）

        // 2. 查询漂流瓶
        Bottle bottle = bottleMapper.selectById(bottleId);
        if (bottle == null) {
            return Result.error("漂流瓶不存在或已被删除");
        }

        // 3. 校验当前用户是否为瓶主
        if (!currentUserId.equals(bottle.getUserId())) {
            return Result.error("无权查看：该漂流瓶不属于当前用户");
        }

        // 4. 查询双方所有消息记录（瓶主 ↔ 指定拾取者）
        LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reply::getBottleId, bottleId)
                .and(wrapper -> wrapper
                        .and(w1 -> w1.eq(Reply::getSenderId, currentUserId)
                                .eq(Reply::getReceiverId, targetUserId))
                        .or(w2 -> w2.eq(Reply::getSenderId, targetUserId)
                                .eq(Reply::getReceiverId, currentUserId))
                )
                .orderByAsc(Reply::getCreateTime);

        List<Reply> replyList = replyMapper.selectList(queryWrapper);

        // 5. 返回结果
        return Result.ok().setData(replyList);
    }
    /**
     * 瓶主回复漂流瓶捞取者
     * 瓶主登录后向指定捞取者发送消息，前端必须传入 bottleId 和 receiverId（拾取者ID）
     */
    @PostMapping("/ownerReplyBottle")
    public Result ownerReplyBottle(@RequestBody Reply reply) {
        // 1. 参数校验
        if (reply == null || reply.getBottleId() == null || reply.getReceiverId() == null) {
            return Result.error("参数错误：bottleId和receiverId不能为空");
        }

        Long currentUserId = UserUtils.getCurrentLoginId(); // 当前登录用户（瓶主）

        // 2. 查询漂流瓶并校验瓶主身份
        Bottle bottle = bottleMapper.selectById(reply.getBottleId());
        if (bottle == null) {
            return Result.error("漂流瓶不存在或已被删除");
        }
        if (!currentUserId.equals(bottle.getUserId())) {
            return Result.error("无权操作：该漂流瓶不属于当前用户");
        }

        // 3. 填充消息信息
        reply.setSenderId(currentUserId);
        reply.setCreateTime(LocalDateTime.now());
        // receiverId 已由前端传入（拾取者ID）

        // 4. 插入数据库
        int inserted = replyMapper.insert(reply);
        if (inserted <= 0) {
            return Result.error("回复失败");
        }

        return Result.ok("瓶主回复成功");
    }



}
